/*
Dominique Jannone
Guillaume Marre
Yohan Ojeda
Laurent Schiavon
*/
package model;

import java.io.IOException;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.ServerSocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.sql.*;


class CanalUserHandler  extends Thread{
	
	// log
	public static final Logger logger = Logger.getLogger(ConnexionDb.class.getName());
	
	private MainServer mainServer;
	static ServerSocketChannel serverSocket;
	private final ExecutorService pool;
	private int cpt = 0;
	private MainServer serveur;
	private ConnexionDb connexion;
	private CanalAnnonceurHandler canalAnnonceur;

	int getCpt(){
	    return cpt;
	}

	CanalUserHandler(int port, ExecutorService pool, MainServer mainServer, CanalAnnonceurHandler canalAnnonceur){
		logger.log(Level.INFO,"Start CanalUserHandler on port " + port );
		serveur = mainServer;
		this.canalAnnonceur = canalAnnonceur;
	    this.pool = pool;
	    try {
		serverSocket = ServerSocketChannel.open();
		serverSocket.socket().bind(new InetSocketAddress(port));
		
		
		// Etablissement Connexion base de donnÃ©es
				
		 connexion = new ConnexionDb();
			
		
		try {
				connexion.etablissementConnexion();
			}			  
			catch (Exception e){logger.log(Level.SEVERE,e.getClass() + ": " +  e.getMessage(), e);}
			finally {
			//connexion.fermetureConnexion();
			}
	    }catch(IOException e){
	    	logger.log(Level.SEVERE,"Start CanalUserHandler on port " + port );
		System.exit(1);
	    }
	
	}
	
	public void run(){
	  Socket sock;
	    try {
		while (mainServer.isServerOn()) {
		    try{
			sock =  serverSocket.accept().socket();
			mainServer.userServiceCpt++;
			pool.execute(new UserServerDelegate(sock,cpt++, serveur, connexion, canalAnnonceur));
		    }catch(ClosedByInterruptException e){logger.log(Level.SEVERE,e.getClass() + ": " +  e.getMessage(), e);}
		}	
		
	    } catch (IOException ex) {  pool.shutdown();  }
	
    }
}
// fin de la classe
